package com.mbschenkel.client;


import java.util.Date;

import javax.servlet.http.HttpServletRequest;

import com.google.gwt.core.client.GWT;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.ServiceDefTarget;
import com.google.gwt.user.client.ui.*;
import com.google.gwt.user.client.ui.FlexTable.FlexCellFormatter;
import com.mbschenkel.client.LatexService;
import com.mbschenkel.client.LatexServiceAsync;

/**
 * This is a singleton (one instance per Client) class holding all "global" information.
 * E.g. asynchronous connection, session and user data, app. state etc.
 * @author mbs
 *
 */
public class Session { 
	public SessionData sessionData = new SessionData();
	public SessionData getSessionData() { return sessionData; }
	public LatexServiceAsync latexService;
	private Panel sessionPanel = null;
	public Panel getSessionPanel() {
		if( sessionPanel == null) {
			sessionPanel = new VerticalPanel();

			// initial call
			updateSessionPanel();
			sessionData.syncRemotely();
		}
		return sessionPanel;
	}
	public void updateSessionPanel() {
		sessionPanel.clear();
		Button updateButton = new Button("update", new ClickListener() {
			public void onClick(Widget sender) {
				updateSessionPanel();
			}
		});
		Button logoutButton = new Button("logout", new ClickListener() {
			public void onClick(Widget sender) {
				// TODO experimental
				sessionData.clear(); 
				sessionData.syncRemotely();
			}
		});
		sessionPanel.add(updateButton);
		sessionPanel.add(logoutButton);
		Date today = new Date();

		sessionPanel.add(new HTML("<h3>Session info</h3><ul>" +
				"<li>User Name: "+sessionData.userName+
				"<li>Email: "+sessionData.emailAddress+
				"<li>User ID: "+sessionData.userID+
				"<li>Session ID: "+sessionData.sessionID+
				"<li>Session Secret: "+sessionData.sessionSecret+
				"<li>Trust Level: "+sessionData.trustLevel+
				"<li>Current Time: "+DateTimeFormat.getLongTimeFormat().format(today)+
				"</ul>")
		);
		
		if(sessionData.userID == -1){
		    // Create a table to layout the form options
		    FlexTable layout = new FlexTable();
		    layout.setCellSpacing(6);
		    FlexCellFormatter cellFormatter = layout.getFlexCellFormatter();

		    // Add a title to the form
		    layout.setHTML(0, 0, Images.buildHTML(Images.getUser())+" Login for returning users");
		    cellFormatter.setColSpan(0, 0, 2);
		    cellFormatter.setHorizontalAlignment(0, 0, HasHorizontalAlignment.ALIGN_CENTER);

		    final TextBox userNameBox = new TextBox();
		    final PasswordTextBox pwdBox = new PasswordTextBox();
		    userNameBox.setText("mbs"); // TODO remove
		    pwdBox.setText("a");		// TODO remove
		    // Add some standard form options
		    layout.setHTML(1, 0, "Username" );
		    layout.setWidget(1, 1, userNameBox );
		    layout.setHTML(2, 0, "Password");
		    layout.setWidget(2, 1, pwdBox);
		    layout.setWidget(3, 1, new Button("Submit",new ClickListener(){
				public void onClick(Widget sender) {
					sessionData.loginRequestName = userNameBox.getText();
					if(sessionData.loginRequestName.isEmpty()){
						Window.alert("user name is empty");
					}else{
						String pwdHashed = Hash.hashContent(pwdBox.getText());
						sessionData.loginRequestPasswordHash = pwdHashed;
						sessionData.syncRemotely();
					}
				}
		    }));

		    // Wrap the content in a DecoratorPanel
		    DecoratorPanel loginPanel = new DecoratorPanel();
		    loginPanel.setWidget(layout);
		    sessionPanel.add(loginPanel);
		}
	}
	/**
	 * Private constructor -> ensures singleton behaviour
	 */
	private Session() {
		/* async service related stuff */
		latexService = (LatexServiceAsync) GWT.create(LatexService.class);
		ServiceDefTarget endpoint = (ServiceDefTarget) latexService;
		String moduleRelativeURL = GWT.getModuleBaseURL() + "LatexService";
		endpoint.setServiceEntryPoint(moduleRelativeURL);

		// do not initialize panel here to prevent loop with access to async-interface
	}
	/** 
	 * The singleton
	 */
	private static Session instance = new Session();
	/** 
	 * Access the singleton
	 * @return the singleton
	 */
	public static Session getInstance() {
		return instance;
	}
	
	
}
 